import { isDevice } from '@/utils/commonutils'
import { uploadAttachment } from '@/api/workcard'
import { getUsername } from '@/utils/auth'

// 附件保存在 cordova.file.dataDirectory/{username}_{id}/ 下面
/* eslint-disable no-undef */
function saveAttachment(id, filename, dataObj) {
  if (!isDevice()) {
    return
  }

  const subfolder = _getSubFolder(id)

  // const path = cordova.file.dataDirectory
  _saveFile(subfolder, filename, dataObj)
}

// 照片保存在 cordova.file.dataDirectory/{username}_{id}/ 下面
/* eslint-disable no-undef */
function savePhoto(id, filename, dataObj) {
  // let path = cordova.file.cacheDirectory
  if (!isDevice()) {
    return
  }

  const subfolder = _getSubFolder(id)

  _saveFile(subfolder, filename, dataObj)
}

/* eslint-disable no-undef */
function _saveFile(subfolder, filename, dataObj) {
  if (isDevice()) {
    var rootpath = cordova.file.dataDirectory

    // support ios
    window.resolveLocalFileSystemURL(rootpath, function(dirEntry) {
      console.log('saved path: ' + rootpath)
      console.log('file system open: ' + dirEntry.name)
      _createDirectory(dirEntry, subfolder)
    }, _onErrorLoadFs)
  } else {
    // support chrome，safari，firefox，ie and edge
    console.log('only support mobile device, other platform does not support!')
    return
  }

  function _createDirectory(directoryEntry, dirname) {
    directoryEntry.getDirectory(
      dirname,
      { create: true, exclusive: false },
      onGetDirectoryWin,
      onGetDirectoryFail
    )

    function onGetDirectoryWin(newDirEntry) {
      console.log('目录获得或创建成功：' + newDirEntry.toURL())
      _createFile(newDirEntry, filename, dataObj)
    }

    function onGetDirectoryFail(err) {
      console.log('目录创建失败：' + err)
    }
  }

  function _createFile(dirEntry, fileName, dataObj) {
    // Creates a new file or returns the file if it already exists.
    dirEntry.getFile(fileName, {
      create: true,
      exclusive: false
    }, function(fileEntry) {
      _writeFile(fileEntry, dataObj)
    }, _onErrorCreateFile)
  }

  function _writeFile(fileEntry, dataObj) {
    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function(fileWriter) {
      fileWriter.onwriteend = function() {
        console.log('Successful file read...')
      }

      fileWriter.onerror = function(e) {
        console.log('Failed file read: ' + e.toString())
      }

      // If we are appending data to file, go to the end of the file.
      fileWriter.write(dataObj)
    })
  }
}

// 把文件从source目录拷贝到cordova.file.dataDirectory/{username}_{id}/ 下面
// sourceFilePath: 源文件路径，前面包含"file:///"
// fileName: 源文件名称

function copyFile(id, sourceFilePath, sourceFileName) {
  return new Promise(
    (resolve, reject) => {
      if (!isDevice()) {
        resolve({})
      }
      var _sourceFilePath = sourceFilePath
      var _sourceFileName = sourceFileName
      console.log('sourceFullFilePath: ' + sourceFilePath)
      console.log('sourceFileName: ' + sourceFileName)

      // 不支持相对路径，如果不是以'/'或'file:///'开头，返回为空
      if (!_sourceFilePath.startsWith('file:///')) {
        if (_sourceFilePath.startsWith('/')) {
          _sourceFilePath = 'file:///' + sourceFilePath
        } else {
          reject('Error! Source path need begin with "/" or "file:///"')
        }
      }

      // |>. 获取源文件路径
      window.resolveLocalFileSystemURL(_sourceFilePath, function(dirEntry) {
        console.log('file system open: ' + dirEntry.name)
        // |>|>. 拷贝文件
        _copyFile(dirEntry, _sourceFileName)
      }, _onErrorLoadSourcePathWhenCopy)

      function _onErrorLoadSourcePathWhenCopy(e) {
        const error = 'errors in _onErrorLoadSourcePathWhenCopy: ' + JSON.stringify(e)
        console.log(error)
        reject(error)
      }

      function _copyFile(dirEntry, sourceFileName) {
        // |>|>|>. 读源文件，看存不存在
        dirEntry.getFile(sourceFileName, {
          create: false,
          exclusive: false
        }, function(sourceFileEntry) {
          const targetRootPath = cordova.file.dataDirectory
          const targetSubFolder = _getSubFolder(id)

          // |>|>|>|>. 读目标根目录
          window.resolveLocalFileSystemURL(targetRootPath, function(targetDirEntry) {
            console.log('root target path for copy: ' + targetRootPath)
            console.log('target folder for copy: ' + dirEntry.name)
            _createDirectoryBeforeCopy(sourceFileEntry, targetDirEntry, targetSubFolder, sourceFileName)
          }, _onErrorLoadTargetRootPath)
        }, _onErrorReadSourceFile)

        function _onErrorReadSourceFile(e) {
          const err = 'read source file error when copy: ' + JSON.stringify(e)
          console.log(err)
          reject(err)
        }

        function _onErrorLoadTargetRootPath(e) {
          const err = 'load target root path error when copy: ' + JSON.stringify(e)
          console.log(err)
          reject(err)
        }
      }

      function _createDirectoryBeforeCopy(sourceFileEntry, targetDirEntry, targetSubFolder, targetFileName) {
        targetDirEntry.getDirectory(
          targetSubFolder,
          { create: true, exclusive: false },
          _onSuccessLoadTargetSubFolder,
          _onErrorLoadTargetSubFolder
        )

        function _onSuccessLoadTargetSubFolder(newDirEntry) {
          console.log('Target folder create or get success before copy：' + newDirEntry.toURL())

          const _toFilePath = _getFilePath(id)
          window.resolveLocalFileSystemURL(_toFilePath, function(_toDirEntry) {
            sourceFileEntry.copyTo(_toDirEntry, targetFileName, _onSuccessCopy, _onErrorCopy)
          }, _onErrorLoadTargetFolderCopy)

          function _onSuccessCopy(fileEntry) {
            console.log('copy file success: ' + fileEntry.toURL())
            resolve(fileEntry.toURL())
          }

          function _onErrorCopy(e) {
            const err = 'error when copy file:' + JSON.stringify(e)
            console.log(err)
            reject(err)
          }

          function _onErrorLoadTargetFolderCopy(e) {
            const err = 'errors when load target folder before copy: ' + JSON.stringify(e)
            console.log(err)
            reject(err)
          }
        }

        function _onErrorLoadTargetSubFolder(e) {
          const err = 'Target subfolder create or get failed before copy：' + JSON.stringify(e)
          console.log(err)
          reject(err)
        }
      }
    }
  )
  // if (isDevice()) {
  //   console.log('sourceFullFilePath: ' + sourceFilePath)
  //   console.log('sourceFileName: ' + sourceFileName)

  //   window.resolveLocalFileSystemURL(sourceFilePath, function(dirEntry) {
  //     console.log('file system open: ' + dirEntry.name)
  //     _copyFile(dirEntry, sourceFileName)
  //   }, _onErrorLoadFs)
  // } else {
  //   // support chrome，safari，firefox，ie and edge
  //   console.log('only support mobile device, other platform does not support!')
  //   return
  // }
  // function _copyFile(dirEntry, fileName) {
  //   // returns the file if it already exists.
  //   dirEntry.getFile(fileName, {
  //     create: false,
  //     exclusive: false
  //   }, function(fileEntry) {
  //     const username = getUsername()
  //     const subfolder = username + '_' + id + '/'
  //     const filePath = cordova.file.dataDirectory + subfolder

  //     fileEntry.copyTo(filePath, fileName, function(fileEntry) {
  //       console.log('copy file success: ' + fileEntry.fullPath + '/' + fileEntry.name)
  //     }, _onErrorReadFile)
  //     // _readBinaryFileAndCopy(fileEntry)
  //   }, _onErrorReadFile)
  // }

  // function _readBinaryFileAndCopy(fileEntry) {
  //   fileEntry.file(function(file) {
  //     var reader = new FileReader()
  //     reader.onloadend = function() {
  //       console.log('Successful file write: ' + this.result)
  //       var blob = new Blob([new Uint8Array(this.result)], { type: 'image/jpeg' })
  //       saveFile(fileEntry.name, blob)
  //     }
  //     reader.readAsArrayBuffer(file)
  //   }, _onErrorReadFile)
  // }
}

// id - 工卡ID
// fileName - 需要显示的文件名称
// return fileObj with promise - 把需要显示的文件放在fileObj中, fileObj是fileEntry.toURL()
function prepareToDisplay(id, fileName) {
  return new Promise(
    (resolve, reject) => {
      const filePath = _getFilePath(id)
      if (isDevice()) {
        window.resolveLocalFileSystemURL(filePath, function(fileEntry) {
          _readFile(fileEntry)
        }, _onErrorLoadFsInPrepareToDisplay)
      } else {
        // TODO: support chrome，safari，firefox，ie and edge
        console.log('only support ios, other platform does not support!')
        reject(fileName)
      }

      function _readFile(fileEntry) {
        fileEntry.getFile(fileName, {
          create: false,
          exclusive: false
        },
        function(fileEntry) {
          const fileObj = {}
          fileObj.name = decodeURI(fileEntry.name)
          fileObj.dataURL = decodeURI(fileEntry.toURL())
          console.log(fileObj)
          resolve(fileObj)
        }, _onErrorReadFileInPrepareToDisplay)
      }

      function _onErrorLoadFsInPrepareToDisplay(e) {
        console.log('errors in _onErrorLoadFsInPrepareToDisplay: ' + JSON.stringify(e))
        reject(e)
      }

      function _onErrorReadFileInPrepareToDisplay(e) {
        console.log('errors in _onErrorReadFileInPrepareToDisplay: ' + JSON.stringify(e))
        reject(e)
      }
    }
  )
}

function _onErrorLoadFs(e) {
  console.log('errors in _onErrorLoadFs: ' + JSON.stringify(e))
}

function _onErrorCreateFile(e) {
  if (e.toString() !== 'Canceled') {
    console.log('errors in _onErrorCreateFile: ' + JSON.stringify(e))
    // that.$message({
    //   message: '文件打开错误！',
    //   type: 'error'
    // })
  }
}

// function _onErrorReadFile(e) {
//   if (e.toString() !== 'Canceled') {
//     console.log('errors in _onErrorReadFile: ' + JSON.stringify(e))
//   }
// }

// 根据全路径返回文件名称
// fullPath - fullpath with filename
// eg: fullPath = '/data/user/0/io.cordova.hellocordova/cache/ImagePicker/1549933907296644.jpeg'
function getFileName(fullPath) {
  if (!fullPath) { // 如果fullPath为空，返回
    return ''
  }
  if ((fullPath.lastIndexOf('/') + 1) === fullPath.length) { // 如果只有路径，不带文件名，返回为空
    return ''
  }
  return fullPath.substring(fullPath.lastIndexOf('/') + 1)
}

// directory - full file path
// fileName - attachment.path
function showFile(id, fileName) {
  if (!isDevice()) {
    return
  }

  const filePath = _getFilePath(id)
  const fullFillPath = filePath + fileName

  if (_isDefaultOpenFile(fileName)) {
    cordova.plugins.fileOpener2.open(
      fullFillPath,
      'application/*',
      {
        error: function(e) {
          console.log('Error status: ' + e.status + ' - Error message: ' + e.message)
          // that.$message({
          //   message: '文件打开错误！',
          //   type: 'error'
          // })
        },
        success: function() {
          console.log('file ' + fileName + 'opened successfully')
        }
      }
    )
  } else {
    cordova.plugins.fileOpener2.showOpenWithDialog(
      fullFillPath,
      'application/*',
      {
        error: function(e) {
          console.log('Error status: ' + e.status + ' - Error message: ' + e.message)
          // that.$message({
          //   message: '文件打开错误！',
          //   type: 'error'
          // })
        },
        success: function() {
          console.log('file opened successfully')
        }
      }
    )
  }
}

function _isDefaultOpenFile(fileName) {
  if (!fileName) {
    return false
  }
  return fileName.toLowerCase().endsWith('.jpeg') ||
         fileName.toLowerCase().endsWith('.png') ||
         fileName.toLowerCase().endsWith('.jpg') ||
         fileName.toLowerCase().endsWith('.pdf')
}

function _deleteFile(path, filename) {
  window.resolveLocalFileSystemURL(path, function(dir) {
    dir.getFile(filename, { create: false }, function(fileEntry) {
      fileEntry.remove(function() {
        console.log('remove file success: ' + filename)
      }, function(error) {
        throw error
      }, function() {
        console.log('remove failed, file does not exist: ' + filename)
      })
    })
  })
}

// 所有照片和附件保存在"cordova.file.dataDirectory/{username}_{id}/"下面
function deletePhoto(id, filename) {
  if (!isDevice()) {
    return
  }

  const filePath = _getFilePath(id)

  _deleteFile(filePath, filename)
}

function deleteAttachment(id, filename) {
  if (!isDevice()) {
    return
  }

  const path = _getFilePath(id)

  _deleteFile(path, filename)
}

function uploadPhoto(id, photoObject) {
  return new Promise(
    (resolve, reject) => {
      if (!isDevice()) {
        resolve({})
      }

      const filePath = _getFilePath(id)
      const fullFilePath = filePath + photoObject.path

      window.resolveLocalFileSystemURL(
        fullFilePath, _upload, _error
      )

      function _upload(fileEntry) {
        console.log('[file]-[uploadPhoto]-got a file entry: ' + fileEntry.toURL())
        uploadAttachment(fileEntry).then(
          uid => {
            photoObject.uid = uid
            console.log('[file]-[uploadPhoto]-success upload: ' + JSON.stringify(photoObject))
            resolve(photoObject)
          },
          err => {
            reject(err)
          }
        )
      }

      function _error(err) {
        console.log('[file]-[uploadPhoto]-Error resolving fs url', JSON.stringify(err))
        reject(err)
      }
    }
  )
}

function _getSubFolder(id) {
  const username = getUsername()
  const subFolder = username + '_' + id + '/'
  return subFolder
}

function _getFilePath(id) {
  const subFolder = _getSubFolder(id)
  const filePath = cordova.file.dataDirectory + subFolder
  return filePath
}

export {
  saveAttachment,
  savePhoto,
  showFile,
  copyFile,
  deletePhoto,
  deleteAttachment,
  prepareToDisplay,
  getFileName,
  uploadPhoto
}
